#!/usr/bin/env python3
"""
企业混合App后端API - 简化版本
使用模拟JSON数据，不依赖数据库
"""

from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import urllib.parse
import time
import hashlib
from datetime import datetime, timedelta

# 模拟数据
USERS_DATA = {
    "admin": {
        "id": 1,
        "username": "admin",
        "password": hashlib.sha256("admin123".encode()).hexdigest(),
        "name": "管理员",
        "avatar": "https://example.com/avatar.jpg",
        "department": "信息技术部",
        "email": "admin@company.com",
        "phone": "13800138000"
    },
    "user1": {
        "id": 2,
        "username": "user1", 
        "password": hashlib.sha256("user123".encode()).hexdigest(),
        "name": "张三",
        "avatar": "https://example.com/avatar2.jpg",
        "department": "销售部",
        "email": "zhangsan@company.com",
        "phone": "13800138001"
    }
}

# 模拟Token存储
ACTIVE_TOKENS = {}

def create_token(user_id, username):
    """创建简单的token"""
    token_data = f"{user_id}:{username}:{time.time()}"
    token = hashlib.sha256(token_data.encode()).hexdigest()
    ACTIVE_TOKENS[token] = {
        "user_id": user_id,
        "username": username,
        "created_at": time.time()
    }
    return token

def verify_token(token):
    """验证token"""
    if not token:
        return {"error": "missing_token", "message": "认证令牌缺失"}
    
    if token not in ACTIVE_TOKENS:
        return {"error": "invalid_token", "message": "无效的认证令牌"}
    
    token_info = ACTIVE_TOKENS[token]
    # Token有效期2小时
    if time.time() - token_info["created_at"] >= 7200:
        # 清理过期token
        del ACTIVE_TOKENS[token]
        return {"error": "expired_token", "message": "认证令牌已过期"}
    
    return token_info

def get_home_data():
    """获取首页数据"""
    return {
        "banners": [
            {
                "id": 1,
                "title": "企业文化建设",
                "image": "https://example.com/banner1.jpg",
                "url": "/news/1",
                "sort_order": 1
            },
            {
                "id": 2,
                "title": "新产品发布",
                "image": "https://example.com/banner2.jpg",
                "url": "/news/2",
                "sort_order": 2
            },
            {
                "id": 3,
                "title": "团队建设活动",
                "image": "https://example.com/banner3.jpg",
                "url": "/news/3",
                "sort_order": 3
            }
        ],
        "news": [
            {
                "id": 1,
                "title": "公司荣获行业优秀企业奖",
                "summary": "在2024年度行业评选中，我公司凭借优异表现荣获优秀企业奖",
                "content": "详细内容...",
                "author": "企业宣传部",
                "publishTime": "2024-01-15T10:00:00Z",
                "readCount": 156,
                "category": "企业荣誉",
                "image": "https://example.com/news1.jpg"
            },
            {
                "id": 2,
                "title": "新办公楼正式启用",
                "summary": "经过半年的建设，公司新办公楼今日正式启用",
                "content": "详细内容...",
                "author": "行政部",
                "publishTime": "2024-01-14T14:30:00Z",
                "readCount": 89,
                "category": "公司动态",
                "image": "https://example.com/news2.jpg"
            },
            {
                "id": 3,
                "title": "员工技能培训计划启动",
                "summary": "为提升员工专业技能，公司启动全员技能培训计划",
                "content": "详细内容...",
                "author": "人力资源部",
                "publishTime": "2024-01-13T09:00:00Z",
                "readCount": 234,
                "category": "培训发展",
                "image": "https://example.com/news3.jpg"
            }
        ]
    }

def get_apps_list():
    """获取应用列表"""
    return {
        "categories": [
            {
                "title": "办公应用",
                "apps": [
                    {
                        "name": "考勤打卡",
                        "icon": "access_time",
                        "color": "0xFF3366CC"
                    },
                    {
                        "name": "日程管理",
                        "icon": "event",
                        "color": "0xFF4CAF50"
                    },
                    {
                        "name": "文档管理",
                        "icon": "description",
                        "color": "0xFF2196F3"
                    }
                ]
            },
            {
                "title": "人事管理",
                "apps": [
                    {
                        "name": "请假申请",
                        "icon": "event_busy",
                        "color": "0xFFFF9800"
                    },
                    {
                        "name": "员工信息",
                        "icon": "person",
                        "color": "0xFF9C27B0"
                    },
                    {
                        "name": "培训中心",
                        "icon": "school",
                        "color": "0xFF607D8B"
                    }
                ]
            },
            {
                "title": "财务管理",
                "apps": [
                    {
                        "name": "报销管理",
                        "icon": "receipt",
                        "color": "0xFFF44336"
                    },
                    {
                        "name": "工资查询",
                        "icon": "account_balance_wallet",
                        "color": "0xFF795548"
                    },
                    {
                        "name": "财务报表",
                        "icon": "assessment",
                        "color": "0xFF009688"
                    }
                ]
            }
        ]
    }

def get_messages_list():
    """获取消息列表"""
    return {
        "messages": [
            {
                "id": 1,
                "title": "会议通知",
                "content": "明天上午10点召开部门例会",
                "message_type": "meeting",
                "priority": "high",
                "is_read": False,
                "created_at": "2024-01-15T08:00:00Z"
            },
            {
                "id": 2,
                "title": "系统更新",
                "content": "系统将在今晚进行更新维护",
                "message_type": "system",
                "priority": "medium",
                "is_read": True,
                "created_at": "2024-01-14T16:00:00Z"
            }
        ],
        "unread_count": 1,
        "total_count": 2
    }

def get_workspace_apps():
    """获取工作台常用应用"""
    return {
        "favoriteApps": [
            {
                "id": 1,
                "name": "日程管理",
                "icon": "calendar_today",
                "color": "0xFF3366CC",
                "url": "https://calendar.example.com",
                "description": "管理日程安排",
                "sort": 1
            },
            {
                "id": 2,
                "name": "任务协作",
                "icon": "assignment",
                "color": "0xFFFF9900",
                "url": "https://tasks.example.com",
                "description": "团队任务协作",
                "sort": 2
            },
            {
                "id": 3,
                "name": "文档中心",
                "icon": "description",
                "color": "0xFF52C41A",
                "url": "https://docs.example.com",
                "description": "文档管理中心",
                "sort": 3
            },
            {
                "id": 4,
                "name": "考勤打卡",
                "icon": "access_time",
                "color": "0xFF1890FF",
                "url": "https://attendance.example.com",
                "description": "员工考勤管理",
                "sort": 4
            },
            {
                "id": 5,
                "name": "报销管理",
                "icon": "receipt",
                "color": "0xFFEB2F96",
                "url": "https://expense.example.com",
                "description": "费用报销申请",
                "sort": 5
            },
            {
                "id": 6,
                "name": "通讯录",
                "icon": "contacts",
                "color": "0xFF722ED1",
                "url": "https://contacts.example.com",
                "description": "企业通讯录",
                "sort": 6
            }
        ]
    }

class APIHandler(BaseHTTPRequestHandler):
    def do_OPTIONS(self):
        """处理CORS预检请求"""
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
        self.end_headers()
    
    def do_GET(self):
        """处理GET请求"""
        self.handle_request('GET')
    
    def do_POST(self):
        """处理POST请求"""
        self.handle_request('POST')
    
    def do_PUT(self):
        """处理PUT请求"""
        self.handle_request('PUT')
    
    def do_DELETE(self):
        """处理DELETE请求"""
        self.handle_request('DELETE')
    
    def handle_request(self, method):
        """统一处理请求"""
        try:
            # 解析路径
            parsed_path = urllib.parse.urlparse(self.path)
            path = parsed_path.path
            query_params = urllib.parse.parse_qs(parsed_path.query)
            
            # 获取请求体
            content_length = int(self.headers.get('Content-Length', 0))
            post_data = self.rfile.read(content_length) if content_length > 0 else b''
            
            # 获取Authorization头
            auth_header = self.headers.get('Authorization', '')
            token = auth_header.replace('Bearer ', '') if auth_header.startswith('Bearer ') else None
            
            # 路由处理
            response = self.route_request(method, path, post_data, token, query_params)
            
            # 发送响应
            self.send_json_response(response)
            
        except Exception as e:
            error_response = {
                "success": False,
                "message": "服务器内部错误",
                "error": str(e),
                "timestamp": int(time.time())
            }
            self.send_json_response(error_response, status_code=500)
    
    def route_request(self, method, path, post_data, token, query_params):
        """路由处理"""
        
        # 根路径
        if path == '/':
            return {
                "success": True,
                "message": "企业混合App后端API服务运行正常",
                "data": {
                    "version": "1.0.0",
                    "status": "running",
                    "environment": "development"
                },
                "timestamp": int(time.time())
            }
        
        # 系统接口
        elif path == '/api/system/ping':
            return {
                "success": True,
                "message": "pong",
                "data": {"server_time": datetime.now().isoformat()},
                "timestamp": int(time.time())
            }
        
        elif path == '/api/system/info':
            return {
                "success": True,
                "message": "获取服务器信息成功",
                "data": {
                    "server_name": "企业混合App后端服务",
                    "version": "1.0.0",
                    "api_version": "v1",
                    "environment": "development"
                },
                "timestamp": int(time.time())
            }
        
        # 认证接口
        elif path == '/api/auth/login' and method == 'POST':
            return self.handle_login(post_data)
        
        elif path == '/api/auth/logout' and method == 'POST':
            return self.handle_logout(token)
        
        # 需要认证的接口
        elif token:
            user_info = verify_token(token)
            if "error" in user_info:
                return self.create_auth_error_response(token, user_info)
            
            # 首页接口
            if path == '/api/home/info':
                return {
                    "success": True,
                    "message": "获取首页信息成功",
                    "data": get_home_data(),
                    "timestamp": int(time.time())
                }
            
            # 应用接口
            elif path == '/api/apps/list':
                return {
                    "success": True,
                    "message": "获取应用列表成功",
                    "data": get_apps_list(),
                    "timestamp": int(time.time())
                }
            
            # 消息接口
            elif path == '/api/messages/list':
                return {
                    "success": True,
                    "message": "获取消息列表成功",
                    "data": get_messages_list(),
                    "timestamp": int(time.time())
                }
            
            # 工作台接口
            elif path == '/api/workspace/apps':
                return {
                    "success": True,
                    "message": "获取成功",
                    "data": get_workspace_apps(),
                    "timestamp": int(time.time())
                }
            
            # 用户信息接口
            elif path == '/api/user/profile':
                username = user_info['username']
                user_data = USERS_DATA.get(username, {})
                return {
                    "success": True,
                    "message": "获取用户信息成功",
                    "data": {
                        "id": user_data.get("id"),
                        "username": user_data.get("username"),
                        "name": user_data.get("name"),
                        "avatar": user_data.get("avatar"),
                        "department": user_data.get("department"),
                        "email": user_data.get("email"),
                        "phone": user_data.get("phone")
                    },
                    "timestamp": int(time.time())
                }
        
        # 需要认证但没有提供token的接口
        elif path.startswith('/api/') and path not in ['/api/auth/login', '/api/system/ping', '/api/system/info']:
            return self.create_auth_error_response(None)
        
        # 未找到的路径
        return {
            "success": False,
            "message": "接口不存在",
            "error": "Not Found",
            "timestamp": int(time.time())
        }
    
    def handle_login(self, post_data):
        """处理登录"""
        try:
            login_data = json.loads(post_data.decode('utf-8'))
            username = login_data.get('username')
            password = login_data.get('password')
            
            if not username or not password:
                return {
                    "success": False,
                    "message": "用户名和密码不能为空",
                    "error": "Bad Request",
                    "timestamp": int(time.time())
                }
            
            user = USERS_DATA.get(username)
            if not user:
                return {
                    "success": False,
                    "message": "用户名或密码错误",
                    "error": "Unauthorized",
                    "timestamp": int(time.time())
                }
            
            # 验证密码
            password_hash = hashlib.sha256(password.encode()).hexdigest()
            if user["password"] != password_hash:
                return {
                    "success": False,
                    "message": "用户名或密码错误",
                    "error": "Unauthorized",
                    "timestamp": int(time.time())
                }
            
            # 创建token
            token = create_token(user["id"], username)
            
            return {
                "success": True,
                "message": "登录成功",
                "data": {
                    "token": token,
                    "refreshToken": f"refresh_{token}",
                    "expiresIn": 7200,
                    "user": {
                        "id": user["id"],
                        "username": user["username"],
                        "name": user["name"],
                        "avatar": user.get("avatar"),
                        "department": user.get("department"),
                        "email": user.get("email"),
                        "phone": user.get("phone")
                    }
                },
                "timestamp": int(time.time())
            }
            
        except json.JSONDecodeError:
            return {
                "success": False,
                "message": "请求数据格式错误",
                "error": "Bad Request",
                "timestamp": int(time.time())
            }
    
    def handle_logout(self, token):
        """处理登出"""
        if token and token in ACTIVE_TOKENS:
            del ACTIVE_TOKENS[token]
        
        return {
            "success": True,
            "message": "登出成功",
            "timestamp": int(time.time())
        }
    
    def create_auth_error_response(self, token, error_info=None):
        """创建认证错误响应"""
        if not token:
            # 没有提供token
            response = {
                "success": False,
                "message": "认证令牌缺失",
                "error": "Unauthorized",
                "timestamp": int(time.time())
            }
            status_code = 401
        elif error_info:
            # 根据具体错误类型返回不同状态码和消息
            if error_info["error"] == "expired_token":
                response = {
                    "success": False,
                    "message": "登录已过期，请重新登录",
                    "error": "Token Expired",
                    "timestamp": int(time.time())
                }
                status_code = 401
            elif error_info["error"] == "invalid_token":
                response = {
                    "success": False,
                    "message": "认证失败，无效的令牌",
                    "error": "Invalid Token",
                    "timestamp": int(time.time())
                }
                status_code = 403
            else:
                response = {
                    "success": False,
                    "message": error_info.get("message", "认证失败"),
                    "error": "Unauthorized",
                    "timestamp": int(time.time())
                }
                status_code = 401
        else:
            # 默认认证失败
            response = {
                "success": False,
                "message": "权限不足，请检查认证信息",
                "error": "Forbidden",
                "timestamp": int(time.time())
            }
            status_code = 403
        
        # 设置特殊标记，让send_json_response知道要使用特定状态码
        response["_status_code"] = status_code
        return response
    
    def send_json_response(self, data, status_code=200):
        """发送JSON响应"""
        # 检查是否有特殊状态码标记
        if "_status_code" in data:
            status_code = data.pop("_status_code")
        
        self.send_response(status_code)
        self.send_header('Content-type', 'application/json; charset=utf-8')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
        self.end_headers()
        
        response_json = json.dumps(data, ensure_ascii=False, indent=2)
        self.wfile.write(response_json.encode('utf-8'))
    
    def log_message(self, format, *args):
        """自定义日志格式"""
        print(f"[{self.date_time_string()}] {format % args}")

def main():
    """启动服务器"""
    server_address = ('0.0.0.0', 8080)
    httpd = HTTPServer(server_address, APIHandler)
    
    print("🚀 企业混合App后端API服务启动成功!")
    print(f"📍 服务地址: http://localhost:8080")
    print("📋 可用接口:")
    print("   GET  / - 根路径")
    print("   GET  /api/system/ping - 系统测试")
    print("   GET  /api/system/info - 服务器信息")
    print("   POST /api/auth/login - 用户登录")
    print("   POST /api/auth/logout - 用户登出")
    print("   GET  /api/home/info - 首页信息 (需要认证)")
    print("   GET  /api/apps/list - 应用列表 (需要认证)")
    print("   GET  /api/workspace/apps - 工作台应用 (需要认证)")
    print("   GET  /api/messages/list - 消息列表 (需要认证)")
    print("   GET  /api/user/profile - 用户信息 (需要认证)")
    print("\n🧪 测试账号:")
    print("   用户名: admin, 密码: admin123")
    print("   用户名: user1, 密码: user123")
    print("\n按 Ctrl+C 停止服务器")
    
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("\n🛑 服务器已停止")
        httpd.shutdown()

if __name__ == "__main__":
    main()